package com.ljkj.cordial.chat.presenter.response;

import android.app.Activity;
import android.text.TextUtils;

import com.lanjiu.lib.imclient.ims.IMSUtils;
import com.lanjiu.pro.business.BusinessProtocolEntities;
import com.lanjiu.pro.business.BusinessProtocolMessages;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.bean.EmptyMessageEvent;
import com.ljkj.cordial.chat.bean.MsgType;
import com.ljkj.cordial.chat.dao.ChatTableBean;
import com.ljkj.cordial.chat.dao.DbController;
import com.nic.view.util.JLog;


public class DelGroupMessageProtocolResponse extends AResponseBusinessPresenter {
    @Override
    public void onResponse(Activity activity, boolean isOnScreen, String msgType, Object msg) {
        BusinessProtocolMessages.DelGroupOffMessageProtocol response = (BusinessProtocolMessages.DelGroupOffMessageProtocol) msg;
        String groupId = response.getGroupId();
        String msgIds = response.getMsgIds();
        String memberIds = response.getMemberIds();

        if (!isEmpty(msgIds, memberIds)) {
            String[] msgIdArray = msgIds.split(",");
            String[] memberIdArray = memberIds.split(",");
            if (msgIdArray.length == memberIdArray.length) {
                for (int i = 0; i < msgIdArray.length; i++) {
                    String msgId = msgIdArray[i];
                    String memberId = memberIdArray[i];
                    ChatTableBean u = ChatTableBean.queryNewGroupMsg(groupId, msgId);
                    int chat = Canstants.GROUP_CHAT;
                    if (u != null) {
                        JLog.e(msgId);
                        u.setChatType(MsgType.Del_Chat_Msg);
                        u.setStartReadFinish(false);
                        if (u.getRelateId() != null && u.getRelateId() > 0) {
                            ChatTableBean ut = ChatTableBean.getTableFromId(String.valueOf(u.getRelateId()));
                            ut.setChatType(MsgType.Del_Chat_Msg);
                            DbController.getInstance().getWrite().getChatTableBeanDao().update(ut);
                        }
                        DbController.getInstance().getWrite().getChatTableBeanDao().update(u);
                        postEvent(new EmptyMessageEvent(chat, groupId, "", IMSUtils.userTypeAnalysis(groupId), memberId, msgId, EmptyMessageEvent.REMOVE));
                        refresh(activity);
                    }
                }
            }
        }
    }

    private boolean isEmpty(String... text) {
        if (text == null || text.length == 0)
            return true;
        for (String s : text) {
            if (TextUtils.isEmpty(s)) {
                return true;
            }
        }
        return false;
    }
}
